
import {Injectable} from "@angular/core";
import {SQLite, SQLiteObject} from "@ionic-native/sqlite";
import {Platform} from "ionic-angular";

@Injectable()
export class SqliteService {
  private _db: SQLiteObject;
  private win: any = window;

  constructor(public sqlite: SQLite,
              public platform: Platform) {

  }

  init():Promise<any> {
      return new Promise((resolve, reject) => {
          if (this.platform.is('cordova')) {//native
              if(this.platform.is('ios')){
                  //alert("SqliteService constructor ios!");
                  this.sqlite.create({
                      name: 'appdata.db',
                      iosDatabaseLocation: 'Library'
                  }).then((database:SQLiteObject)=>{
                      this._db = database;
                      alert("create sqlite database success!");
                      resolve(database);
                  },err=>{
                      alert("create sqlite database failed:"+JSON.stringify(err));
                      reject(err);
                  }).catch(err=>{
                      alert("create sqlite database failed:"+JSON.stringify(err));
                      reject(err)
                  });
              }else{
                  //alert("SqliteService constructor not ios!");
                  this.sqlite.create({
                      name: 'appdata.db',
                      location: 'default'
                  }).then((database:SQLiteObject)=>{
                      this._db = database;
                      resolve(database);
                  });
              }
          } else {
              this._db = this.win.openDatabase("appdata.db", '1.0', 'database', 10 * 1024 * 1024);
              resolve();
          }
      });
  }

  /**
   * 执行SQL语句，返回一个承诺,通过 .then(result=>{}).catch(err=>{})来处理结果
   * @param sql  sql语句
   * @param params sql参数值，可选参数，只有sql语句中用到 ? 传参方式时，params参数值才有效
   */
  execSql(sql: string, params = []): Promise<any> {
    return new Promise((resolve, reject) => {
      try {
        this._db.transaction((tx) => {
            tx.executeSql(sql, params,
              (tx, res) => {
                //console.log('execSql success');
                resolve({ tx: tx, res: res })},
              (tx, err) => {
                  console.error('execSql fail:'+JSON.stringify(err));
                reject({ tx: tx, err: err })});
          });
      } catch (err) {
          console.error('execSql fail:'+JSON.stringify(err));
        reject({ err: err });
      }
    });
  }


  get db(): SQLiteObject {
    return this._db;
  }
}
